package com.gitee.wsl.struct.generator

import com.gitee.wsl.func.consumer.Consumer
import kotlinx.atomicfu.atomic


//流 通用接口
//https://my.oschina.net/u/3874284/blog/8691056


fun interface Seq<T> {

    fun consume(consumer: Consumer<T>)

    fun cache(): Seq<T> {
        val arraySeq: SeqList<T> = SeqList()
        consume { t -> arraySeq.add(t) }
        return arraySeq
    }

    fun <E> mapSeq(mapFun:(T)->E):Seq<E>{
       return Seq<E> { consumerFun ->
           consume{ it-> consumerFun.accept(mapFun(it)) }
       }
    }
}

fun interface CreateSeqByItem<T>{
    fun apply(item:T):Seq<T>?
}

object SeqCreate{

    private val uniqueIdGenerator = atomic(0L)

    fun generatorTempId():Long = uniqueIdGenerator.getAndIncrement()


    fun <T> unit(t: T): Seq<T> {
        return Seq<T> { consumer -> consumer.accept(t) }
    }

}


class SeqList<T>(val list: MutableList<T> = mutableListOf()) : MutableList<T> by list,Seq<T>{

    override fun consume(consumer: Consumer<T>) {
        list.forEach{
            consumer.accept(it)
        }
    }

    companion object{
        fun <T>  of(list: List<T>):SeqList<T>{
            return SeqList<T>().apply {
                addAll(list)
            }
        }
    }
}